package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.city.entity.City;
import com.antdesignbackend.backend.common.GoogleAuthenticator;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.district.entity.District;
import com.antdesignbackend.backend.entity.Button;
import com.antdesignbackend.backend.entity.Menu;
import com.antdesignbackend.backend.entity.UserRoles;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.RoleMenuVo;
import com.antdesignbackend.backend.entity.entityVo.UserRoleVo;
import com.antdesignbackend.backend.mapper.RolesMapper;
import com.antdesignbackend.backend.service.PermissionService;
import com.antdesignbackend.backend.service.RoleMenuService;
import com.antdesignbackend.backend.service.UserRolesService;
import com.antdesignbackend.backend.service.UserService;
import com.antdesignbackend.backend.town.entity.Town;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Controller
@RequestMapping("/UserManage")
public class UserController extends BaseController {
    @Autowired
    UserRolesService userRolesService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    UserService userService;
    @Autowired
    RoleMenuService roleMenuService;
    @Autowired
    RolesMapper rolesMapper;


    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;


    @GetMapping("/index")
    @AuthToken
    public String buttonIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "user/index";
    }

    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody UserRoleVo userRoleVo) {
        ReturnVO returnVO = new ReturnVO();
        try {
            QueryWrapper<UserRoleVo> queryWrapper = new QueryWrapper<>();
            //判断用户权限
            Users users = userService.getById(getLoginUserId());
            if (users.getAuthType() == 1){ //地市权限
                queryWrapper.eq("authCity",users.getAuthCity());
            }else if (users.getAuthType() == 2){ //区县权限
                queryWrapper.eq("authDistrict",users.getAuthDistrict());
            }else if (users.getAuthType() == 3){
                queryWrapper.eq("authTown",users.getAuthTown());
            }else {
                return returnVO;
            }
            //根据地市查询
            if(userRoleVo.getAuthCity() != null && userRoleVo.getAuthCity() != -1){
                queryWrapper.eq("authCity",userRoleVo.getAuthCity());
            }
            if(userRoleVo.getAuthDistrict() != null && userRoleVo.getAuthDistrict() != -1){
                queryWrapper.eq("authDistrict",userRoleVo.getAuthDistrict());
            }
            if(userRoleVo.getAuthTown() != null && userRoleVo.getAuthTown() != -1){
                queryWrapper.eq("authTown",userRoleVo.getAuthTown());
            }
            if (userRoleVo.getUserName() != null && !userRoleVo.getUserName().equals(""))
                queryWrapper.eq("userName", userRoleVo.getUserName());
            if (userRoleVo.getUserType() != null && userRoleVo.getUserType() >= 0)
                queryWrapper.eq("userType", userRoleVo.getUserType());
            if (userRoleVo.getActivity() != null && userRoleVo.getActivity() >= 0)
                queryWrapper.eq("activity", userRoleVo.getActivity());
            queryWrapper.ge("r.RoleID", userRoleVo.getRoleID());

            int total = userRolesService.count(queryWrapper);

            if (userRoleVo.getSort() != null && !userRoleVo.getSort().equals("")) {
                if (userRoleVo.getSortOrder().equals("desc"))
                    queryWrapper.orderByDesc(userRoleVo.getSort());
                else
                    queryWrapper.orderByAsc(userRoleVo.getSort());
            }

            List<UserRoleVo> userRoleVos = userRolesService.selectUserRoleList(queryWrapper,
                    new Page<>(userRoleVo.getPageIndex(), userRoleVo.getPageSize()));

            IntStream.range(0, userRoleVos.size()).forEach(i -> {
                UserRoleVo model = userRoleVos.get(i);
                if (model.getParentID() != null) {
                    List<UserRoleVo> filerList = userRoleVos.stream().filter(f -> f.getUserID() == model.getParentID()).collect(Collectors.toList());
                    if (filerList.size() > 0)
                        userRoleVos.get(i).setParentName(filerList.get(0).getUserName());
                }
            });

            //得到当前菜单具备的功能权限
            List<Button> list = permissionService.filterPermission(String.valueOf(userRoleVo.getRoleID()), menuId);
            userRoleVos.forEach(model -> model.setButtonList(list));

            returnVO.setTotal(total);
            returnVO.setData(userRoleVos);
            return returnVO;

        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    @PostMapping("/changeState")
    @ResponseBody
    @AuthToken
    public ReturnVO changeState(@RequestBody Users users) {
        try {
            Users model = new Users();
            model=userService.getById(users.getUserID());
            model.setActivity(users.getActivity());
            QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
            usersQueryWrapper.eq("userID", users.getUserID());
            userService.update(model, usersQueryWrapper);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    @PostMapping("/edit")
    @ResponseBody
    @AuthToken
    public ReturnVO edit(@RequestBody UserRoleVo userRoleVo) {
        try {
            if(userRoleVo.getAuthDistrict() == null || userRoleVo.getAuthDistrict().intValue() == 0){
                userRoleVo.setAuthType(1);
            }else if(userRoleVo.getAuthTown() == null || userRoleVo.getAuthTown().intValue() == 0){
                userRoleVo.setAuthType(2);
            }else{
                userRoleVo.setAuthType(3);
            }
            Users users = new Users();
            users=userService.getById(userRoleVo.getUserID());
            users.setRealName(userRoleVo.getRealName());
            //users.setPassword(DigestUtils.md5DigestAsHex(userRoleVo.getPassword().getBytes()));
            users.setAuthCity(userRoleVo.getAuthCity());
            users.setAuthDistrict(userRoleVo.getAuthDistrict());
            users.setIdCard(userRoleVo.getIdCard());
            users.setAuthTown(userRoleVo.getAuthTown());
            users.setAuthType(userRoleVo.getAuthType());
            users.setWeixinpay(userRoleVo.getWeixinpay());
            users.setUserType(userRoleVo.getRoleID());
            users.setUserName(userRoleVo.getUserName());
            users.setSex(userRoleVo.getSex());
            users.setPhone(userRoleVo.getPhone());
            users.setEmail(userRoleVo.getEmail());
            users.setBankUserName(userRoleVo.getBankUserName());
            users.setBankNo(userRoleVo.getBankNo());
            users.setBankName(userRoleVo.getBankName());
            users.setAlipay(userRoleVo.getAlipay());
            users.setAmount(userRoleVo.getAmount());
            users.setActivity(userRoleVo.getActivity());
            users.setUserID(userRoleVo.getUserID());
            users.setDeptId(userRoleVo.getDeptId());
            QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
            usersQueryWrapper.eq("userID", userRoleVo.getUserID());
            userService.update(users, usersQueryWrapper);

            UserRoles userRoles = new UserRoles();
            userRoles.setUserID(userRoleVo.getUserID());
            userRoles.setRoleID(userRoleVo.getRoleID());
            QueryWrapper<UserRoles> userRolesQueryWrapper = new QueryWrapper<>();
            userRolesQueryWrapper.eq("userID", userRoleVo.getUserID());

            userRolesService.update(userRoles, userRolesQueryWrapper);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 默认创建下一个角色，当前用户不允许创建当前角色或越级别创建
     * 例如超级管理员创建的用户只能是管理员
     * 管理员创建的用户只能是总代理，依此类推
     * <p>
     * 创建用户时，菜单可以选择，功能按钮沿用当前角色的默认权限，需要修改，可以去菜单管理进行修改
     *
     * @param userRoleVo
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    @AuthToken
    public ReturnVO add(@RequestBody UserRoleVo userRoleVo) {
        try {
            ReturnVO result = new ReturnVO();
            QueryWrapper<Users> userWrapper = new QueryWrapper<>();
            userWrapper.eq("UserName",userRoleVo.getUserName());
            if(userService.list(userWrapper).isEmpty() == false){
                result.setMessage("该登录账号已存在！");
                result.setCode("500");
                return result;
            }
            if(userRoleVo.getAuthDistrict() == null || userRoleVo.getAuthDistrict().intValue() == 0){
                userRoleVo.setAuthType(1);
            }else if(userRoleVo.getAuthTown() == null || userRoleVo.getAuthTown().intValue() == 0){
                userRoleVo.setAuthType(2);
            }else{
                userRoleVo.setAuthType(3);
            }
            //存在下级角色，允许新增用户,开启事务，失败回滚
            userRoleVo.setCreateName(getLoginUserName());
            userService.CreateUser(userRoleVo);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    @PostMapping("/addInit")
    @ResponseBody
    @AuthToken
    public ReturnVO addInit(@RequestBody RoleMenuVo roleMenuVo) {
        try {
            QueryWrapper<RoleMenuVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("r.roleID", roleMenuVo.getRoleID());
            List<RoleMenuVo> roleMenuVos = roleMenuService.selectRoleMenuList(queryWrapper, null);

            List<RoleMenuVo> listLevel2 = roleMenuVos.stream().filter(f -> f.getLevel().equals("2")).collect(Collectors.toList());
            List<RoleMenuVo> listIndex = roleMenuVos.stream().filter(f -> f.getId() == 1).collect(Collectors.toList());

            List<Menu> listMenu = new ArrayList<>();
            menuList(listLevel2, listMenu);
            menuList(listIndex, listMenu);

            return new ReturnVO(listMenu);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 根据用户权限查询到对应的 地市，区县，乡镇
     * @return
     */
    @PostMapping("/getAuth")
    @ResponseBody
    @AuthToken
    public ReturnVO getAuth(){
        ReturnVO returnVO = new ReturnVO();
        returnVO.setData(userService.getById(getLoginUserId()));
        return returnVO;
    }

    /**
     * 根据部门id获得审批人
     * @return
     */
    @PostMapping("/getUserByDept")
    @ResponseBody
    @AuthToken
    public List<Users> getUserByDept(@Param("deptId") Integer deptId){
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deptId",deptId);
        queryWrapper.eq("activity",1);
        List<Users> list = userService.list(queryWrapper);
        return list;
    }

    private void menuList(List<RoleMenuVo> listIndex, List<Menu> listMenu) {
        for (RoleMenuVo rv1 : listIndex
        ) {
            Menu menu = new Menu();
            menu.setId(rv1.getId());
            menu.setUrl(rv1.getUrl());
            menu.setTextCH(rv1.getTextCH());
            menu.setLevel(rv1.getLevel());
            menu.setParentID(rv1.getParentID());
            menu.setOrderID(rv1.getOrderID());
            menu.setImageUrl(rv1.getImageUrl());
            menu.setKeyName(rv1.getKeyName());
            listMenu.add(menu);
        }
    }
}
